<template>
	<view class="page bg-fff">
		<detail-banner :aerialObj="productAerial" :vrObj="productVr" :videoObj="productVideo" :product="productDetail" :carousels="panCarousel" :kaiId="kaiId_value" v-if="productDetail.id">
		</detail-banner>

		<detail-title ref="subsDialogRef" :detail="productDetail" :subscribe="subscribe_value" @clickSubs="changeSubs" @update="updateSubs"></detail-title>
		
		<menus :product="productDetail" :kaiId="kaiId_value"></menus>

		<up-tabs :list="kaiPanList" :current="currentPan" lineColor="#007235" keyName="title" :activeStyle="activeStyle" :inactiveStyle="inactiveStyle" @click="changeKaiPan"></up-tabs>

		<pan-price-size :detail="kaiDetail" :product="productDetail"></pan-price-size>

		<ren-gou-msg :detail="kaiDetail"></ren-gou-msg>

		<pan-msg :detail="kaiDetail"></pan-msg>

		<detail-time-line :detail="kaiDetail"></detail-time-line>

		<!-- <seller-list :list="adviserList" :product="productDetail" v-if="adviserList.length > 0"></seller-list> -->
		
		<detail-estate-msg :product="productDetail" :base="product_base"></detail-estate-msg>

		<one-house-one-price-table :list="allBuildingPrices" :product="productDetail" :kaiId="kaiId_value" v-if="allBuildingPrices.length > 0"></one-house-one-price-table>

		<detail-house-type :list="houseTypes" :product="productDetail" :kaiId="kaiId_value" v-if="houseTypes.length > 0"></detail-house-type>

		<detail-around :product="productDetail" v-if="productDetail.lat"></detail-around>

		<up-gap :height="60"></up-gap>

        <up-modal :show="subsDialShow" :showConfirmButton="false" :closeOnClickOverlay="true" @close="subsDialShow = false" @confirm="subsDialShow=false">
			<detail-subscribe-dialog :detail="productDetail" @comfirmAutn="comfirmSubs" @cancelAutn="unAuthSubs"></detail-subscribe-dialog>
		</up-modal>
	</view>
</template>

<script setup>
	import DetailBanner from './components/detail-banner.vue';
	import DetailTitle from './components/detail-title.vue';
	import Menus from './components/menus.vue';
	import PanPriceSize from './components/pan-price-size.vue';
	import RenGouMsg from './components/ren-gou-msg.vue';
	import PanMsg from './components/pan-msg.vue';
	import DetailEstateMsg from './components/detail-estate-msg.vue';
	import DetailAround from './components/detail-around.vue';
	import DetailTimeLine from './components/detail-time-line.vue';
	// import SellerList from './components/seller-list.vue';
	import DetailHouseType from './components/detail-house-type.vue';
	import OneHouseOnePriceTable from './components/one-house-one-price-table.vue';
	import DetailSubscribeDialog from './components/detail-subscribe-dialog.vue';
	import { ref } from 'vue';
	import { useUserInfoStore, useConfigStore } from '@/store/index';
	import { onShow, onLoad, onShareAppMessage, onShareTimeline, onAddToFavorites } from '@dcloudio/uni-app';
	import { isBoolean } from '@/common/common';
	import { createHistory, kaiPanAPI } from "@/common/api";
    import { productDetailAPI, buildingColumnAverageById } from "@/common/api/house";
    import { pyqOpenBeforeAPI, getPageAdAPI, getSimilarAdAPI, bannerAdAPI } from '@/common/api/houses';

	const userInfoStore = useUserInfoStore();
	const configStore = useConfigStore();

	let activeStyle = ref({
		color: '#333333',
		fontWeight: 'bold',
		fontSize: '30rpx'
	});
	let inactiveStyle = {
		color: '#8A8A8A',
		fontSize: '26rpx'
	}

	const subsDialogRef = ref(null);

	//楼盘数据
	let product_id = ref('');
	let title_value = ref('');
	let keywords_value = ref('');
	let share_value = ref(false);
	let productDetail = ref({});
	let productAerial = ref({});
	let productVr = ref({});
	let productVideo = ref({});
	let panCarousel = ref([]);
	let commentList = ref([])
	let commentLength = ref(0)
	let commentUsersLen = ref(0)
	let rqIndex = ref(0)
	let gzIndex = ref(0)
	let subscribe_value = ref(false)
	let subscribeCount = ref()
	let guess = ref([])
	let product_base = ref({})
	let priceList = ref([]);
	let difference = ref('')
	let adviserList = ref([])
	let dynamicList = ref([])
	let articleList = ref([])
	let qrcode = ref('');
	let check_value = ref('')
	let goldSeller = ref(null)
	let allBuildingPrices = ref([]);//一房一价分析表数据


	//开盘数据
	let currentPan = ref(0);
	let kaiPanList = ref([]);
	let kaiId_value = ref('');
	let kaiDetail = ref({})
	let houseTypes = ref([])
	let evaluationList = ref([]);
	let strategyDetail = ref({})
	let product_sun = ref([])
	let fitExcelUrl = ref('')
	let subsDialShow = ref(false)

	// 页面显示
	onShow(() => {
		//延迟1秒再验证验证是否填写上周数据
		setTimeout(async () => {
			await userInfoStore.checkLastWeekVisitData();

			if(userInfoStore.showStatisticsForm) {
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '检测到您上周未提交到访数据，请及时提交',
					success: (res) => {
						if(res.confirm) {
							uni.navigateTo({
								url: `/pages/my/statistics/form/index?startDate=${userInfoStore.statisticsFormObj.start_time}&endDate=${userInfoStore.statisticsFormObj.end_time}`
							})
						}
					}
				})
			}
		}, 1500)
	})

	// 页面加载
	onLoad((options) => {
		let { productId='', title='', keywords = "", puid = '', share=false, from=''} = options;
		product_id.value = productId;
		title_value.value = title&&title!=='undefined'?title:'';
		keywords_value.value = keywords&&keywords!=='undefined'?keywords:'';
		share_value.value = isBoolean(share);
		if (puid&&puid!=='undefined') {
			configStore.setPuid(puid)
		}
		
		//朋友圈进入小程序快照场景
		if(configStore.scene == 1154) {
			pyqOpenBeforeAPI(product_id.value).then(res => {
				productDetail.value = res.detail.product;
			})
			return
		};
		
		//扫码进入场景
		if (options.scene) {
			let scene = decodeURIComponent(options.scene);
			let scene_list = scene.split('&');
			scene_list.forEach(item => {
				let item_list = item.split('=');
				if(item_list.length === 2 && item_list[0] === 'productId'){
					product_id.value = item_list[1]
				}else if(item_list.length === 2 && item_list[0] === 'puid'){
					configStore.setPuid(item_list[1])
				}
				share_value.value = true;
			})
		}

		uni.$check_and_login(initPage)
	})
		
	// 分享到好友
	onShareAppMessage(() => {
		return {
			title: `【${productDetail.value.title}】楼盘信息，点击了解详情`,
			path: `/pages/product/detail/index?productId=${product_id.value}&puid=${userInfoStore.userInfo.id}`,
		}
	})

	// 分享到朋友圈
	onShareTimeline(() => {
		return {
			title: `【${productDetail.value.title}】楼盘信息，点击了解详情`,
			query: `productId=${product_id.value}&puid=${userInfoStore.userInfo.id}&share=true&title=${productDetail.value.title}&prepage=楼盘详情页-${productDetail.value.id}-${productDetail.value.title}`,
		}
	})

	onAddToFavorites(() => {
		return {
			title: `【${productDetail.value.title}】楼盘信息，点击了解详情`,
			query: `productId=${product_id.value}&puid=${userInfoStore.userInfo.id}&share=true&title=${productDetail.value.title}&prepage=楼盘详情页-${productDetail.value.id}-${productDetail.value.title}`
		}
	})

	// 初始化页面
 	async function initPage() {
		await userInfoStore.checkUserInfo();//验证用户信息,如果没有就获取并且更新

		await houseDetail();

		await allBuildingAverage();
		try {
			await createHistory({
				id: product_id.value,
				keywords: keywords_value.value
			})
		} catch (error) {}
	}

	//获取楼盘详情
	async function houseDetail() {
		try {
			const { status, detail } = await productDetailAPI({
				productId: product_id.value,
				puid: configStore.puid,
			});

			if (status !== 0) {
				uni.$u.toast(detail)
				return
			}

			let { product, show_index, subscribe_index, pan, recommend, comment, comment_count, vr, video, fly,
				comment_user_count, subscribe, subscribe_count, around_house_list, around_house_price, base, change,
				seller, news, qr_url, check, mp_xpkf } = detail;
			productDetail.value = product;
			uni.setNavigationBarTitle({
				title: product.title
			});
			productAerial.value = fly.path?fly:{};
			productVideo.value = video.url?video:{};
			productVr.value = vr.vr_url?vr:{};
			// if(comment.length > 0) {
			// 	comment.forEach(item => {
			// 		item.create_time = Date.parse(item.create_time);
			// 		if (item.reply_info.length > 0) {
			// 			item.reply_info.forEach(child => {
			// 				child.create_time = Date.parse(child.create_time)
			// 			})
			// 		}
			// 	})
			// 	commentList.value = comment;
			// }
			// commentLength.value = comment_count;
			// commentUsersLen.value = comment_user_count;
			rqIndex.value = show_index;
			gzIndex.value = subscribe_index;
			subscribe_value.value = subscribe;
			subscribeCount.value = subscribe_count;
			kaiPanList.value = pan;
			guess.value = recommend;
			product_base.value = base;
			priceList.value = around_house_list;
			difference.value = around_house_price;
			adviserList.value = seller;
			dynamicList.value = change;
			articleList.value = news;
			qrcode.value = qr_url;
			check_value.value = check;
			goldSeller.value = seller.find(sellerItem => sellerItem.gold);
			
			kaiId_value.value = kaiId_value.value || (pan.length > 0 ? pan[0].id : '');

			//获取开盘内容
			if(kaiId_value.value) {
				await kaiPanDetail();
			}
		} catch (error) {
			console.log(error)
		}
	}

	//获取开盘数据
	async function kaiPanDetail() {
		try {
			const { status, detail } = await kaiPanAPI({
				kaiId: kaiId_value.value,
			});

			if(status !== 0) {
				uni.$u.toast(detail)
				return;
			}

			let { pan, image, select_house_data, sun, size, evaluate, noise, distance, house_type, fit_excel } = detail;
			kaiDetail.value = pan;
			panCarousel.value = image;
			houseTypes.value = size;
			evaluationList.value = evaluate;
			strategyDetail.value = select_house_data;
			// product_sun.value = sun;
			fitExcelUrl.value = fit_excel;

			// if(noise.length > 0) {
			// 	this.plateBtns.find(item => item.type === 'noise').display = true;
			// }

			// if(distance.length > 0) {
			// 	this.plateBtns.find(item => item.type === 'spacing').display = true;
			// }

			// if(house_type.length > 0) {
			// 	this.plateBtns.find(item => item.type === 'distribution').display = true;
			// }

			uni.hideLoading();
		} catch (error) {
			console.log(error)
		}
	}

	//点击切换开盘
	async function changeKaiPan({index}) {
		kaiId_value.value = kaiPanList.value[index].id;
		await kaiPanDetail();
	}

	//获取楼盘内所有开盘的栋列均价表数据
	async function allBuildingAverage() {
		try {
			let { status, detail } = await buildingColumnAverageById(product_id.value);
			if(status !== 0) {
				uni.$u.toast(detail);
				return
			}

			if(detail.length === 0) return;
			detail.forEach(kaiItem1 => {
				kaiPanList.value.forEach(kaiItem2 => {
					if(kaiItem1.pan_id === kaiItem2.id) {
						kaiItem1.title = kaiItem2.title
					}
				})
			})
			allBuildingPrices.value = detail.filter(item => !item.house_type_empty);;
		} catch (error) {}
	}

	//切换订阅,如果没有订阅就显示弹窗
	function changeSubs() {
		//如果没订阅，没授权
		if(!subscribe_value.value && !userInfoStore.userInfo.shouquan) {
			subsDialShow.value = true;
			return
		}

		console.log(subscribe_value.value)
		subsDialogRef.value.postSubsAuth(subscribe_value.value, userInfoStore.userInfo.phone, userInfoStore.userInfo.shouquan);
		updateSubs();
	}

	//更新订阅
	function updateSubs() {
		if(subscribe_value.value) {
			subscribeCount.value--;
		}else {
			subscribeCount.value++;
			subsDialShow.value = false;
		}
		subscribe_value.value = !subscribe_value.value;
	}

	//确认订阅授权
	function comfirmSubs() {
		subsDialogRef.value.postSubsAuth(subscribe_value.value, userInfoStore.userInfo.phone, true);
		updateSubs();
	}

	//不授权，仅订阅
	function unAuthSubs() {
		subsDialogRef.value.postSubsAuth(subscribe_value.value, userInfoStore.userInfo.phone, false);
		updateSubs();
	}

</script>

<style lang="scss" scoped>
.page{
	min-height: 100vh;
}
</style>
